package memList

import (
	"crypto/md5"
	"encoding/hex"
	"fmt"
	"sync"
	"time"
)

var gTokenMgr *TokenMgr = nil

type TokenMgr struct {
	mapToken map[string]string //key:token value:cmd
	Lock     sync.RWMutex
}

func NewTokenMgr() {
	if gTokenMgr == nil {
		gTokenMgr = &TokenMgr{
			mapToken: make(map[string]string),
		}
	}
}

func GetTokenMgr() *TokenMgr {
	return gTokenMgr
}

func (self *TokenMgr) GeneralToken(cmd string) string {
	self.Lock.Lock()
	defer self.Lock.Unlock()
	tmStamp := time.Now().Unix()
	tmStr := fmt.Sprintf("%ld", tmStamp)
	h := md5.New()
	h.Write([]byte(tmStr))
	cipherStr := h.Sum(nil)
	key := hex.EncodeToString(cipherStr)

	self.mapToken[key] = cmd
	return key
}

//获取token运算
func (self *TokenMgr) GetToken(cmd string, key string) bool {
	self.Lock.RLock()
	defer self.Lock.RUnlock()
	if cmdVal, ok := self.mapToken[key]; ok {
		if cmd == cmdVal {
			return true
		}
	}
	return false
}

func (self *TokenMgr) DelToken(key string) {
	self.Lock.Lock()
	defer self.Lock.Unlock()
	delete(self.mapToken, key)
}
